from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.models.user import User  # 复用用户端的User模型
from app.admin.middleware import admin_required

user_manage_bp = Blueprint('user_manage', __name__, url_prefix='/api/admin/users')

@user_manage_bp.get('')
@jwt_required()
@admin_required()
def get_users():
    """获取用户列表（支持分页和搜索）"""
    page = int(request.args.get('page', 1))
    size = int(request.args.get('size', 10))
    keyword = request.args.get('keyword', '')
    
    # 构建查询条件（按昵称搜索）
    query = {}
    if keyword:
        query["nickname"] = {"$regex": keyword, "$options": "i"}  # 不区分大小写
    
    # 分页查询
    skip = (page - 1) * size
    users = list(User.collection.find(query).skip(skip).limit(size))
    total = User.collection.count_documents(query)
    
    # 转换ObjectId为字符串
    for user in users:
        user["_id"] = str(user["_id"])
    
    return jsonify({
        "code": 0,
        "data": {
            "users": users,
            "total": total,
            "page": page,
            "size": size
        }
    })

@user_manage_bp.delete('/<user_id>')
@jwt_required()
@admin_required()
def delete_user(user_id):
    """删除用户（需超级管理员权限，这里简化处理）"""
    from bson.objectid import ObjectId
    result = User.collection.delete_one({"_id": ObjectId(user_id)})
    if result.deleted_count == 1:
        return jsonify({"code": 0, "msg": "删除成功"})
    return jsonify({"code": -1, "msg": "用户不存在"}), 404